package cn.edu.swu.io;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class ImageManager {
    private Map<String, String> imageMap;
    private static final String SAVE_DIRECTORY = "D:\\Java\\workspace\\2_java_io\\images\\";
    private static final String DATA_FILE = SAVE_DIRECTORY + "image_data.dat";

    public ImageManager() {
        imageMap = new HashMap<>();
        FileUtils.ensureDirectoryExists(SAVE_DIRECTORY);
        loadImageData();
    }

    private void loadImageData(){
        File dataFile = new File(DATA_FILE);
        if (!dataFile.exists()) {
            return;
        }
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(DATA_FILE))) {
            imageMap = (HashMap<String, String>) ois.readObject();
        } catch (Exception e) {
            imageMap = new HashMap<>();
        }
    }

    private void saveImageData() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(DATA_FILE))) {
            oos.writeObject(imageMap);
        } catch (IOException e) {
            System.err.println("保存图片数据失败: " + e.getMessage());
        }
    }

    public void downloadImage(String url) {
        try {
            String fileName = extractFileNameFromUrl(url);
            String savePath = SAVE_DIRECTORY + fileName;

            if (imageMap.containsKey(fileName)) {
                System.out.println("图片已存在: " + fileName);
                System.out.println("路径: " + imageMap.get(fileName));
                return;
            }

            FileUtils.saveImage(url, savePath);

            imageMap.put(fileName, savePath);
            saveImageData();

            System.out.println("图片下载成功: " + fileName);
            System.out.println("保存路径: " + savePath);

        } catch (IOException e) {
            System.err.println("图片下载失败: " + e.getMessage());
        }
    }

    public void listImages() {
        if (imageMap.isEmpty()) {
            System.out.println("暂无已下载的图片");
            return;
        }

        System.out.println("=== 已下载图片列表 ===");
        int index = 1;
        for (Map.Entry<String, String> entry : imageMap.entrySet()) {
            System.out.println(index + ". " + entry.getKey() + " - 路径: " + entry.getValue());
            index++;
        }
        System.out.println("总计: " + imageMap.size() + " 张图片");
    }

    public void searchImage(String name) {
        if (imageMap.isEmpty()) {
            System.out.println("暂无已下载的图片");
            return;
        }

        System.out.println("=== 搜索结果 ===");
        boolean found = false;

        for (Map.Entry<String, String> entry : imageMap.entrySet()) {
            if (entry.getKey().toLowerCase().contains(name.toLowerCase())) {
                System.out.println("找到: " + entry.getKey() + " - 路径: " + entry.getValue());
                found = true;
            }
        }

        if (!found) {
            System.out.println("未找到包含 \"" + name + "\" 的图片");
        }
    }
    private String extractFileNameFromUrl(String url) {

        String cleanUrl = url.split("\\?")[0];

        int lastSlashIndex = cleanUrl.lastIndexOf('/');
        if (lastSlashIndex != -1 && lastSlashIndex < cleanUrl.length() - 1) {
            return cleanUrl.substring(lastSlashIndex + 1);
        }

        return "image_" + System.currentTimeMillis() + ".jpg";
    }

    public int getImageCount() {
        return imageMap.size();
    }
}
